<template>
  <Modal
    v-model="show"
    title="新增政策"
    width="600"
  >
    <Form ref="form" :label-width="80" class="form" :model="form" :rules="rules">
      <FormItem label="政策名称" prop="policyName">
        <Input
          v-model.trim="form.policyName"
          :maxlength="20"
          class="common-width"
          placeholder="请输入2-20位字符的政策名称"
        />
      </FormItem>
      <FormItem label="生效时间" prop="date">
        <DatePicker
          v-model="form.date"
          type="daterange"
          placeholder="请选择生效时间"
          class="common-width"
          @on-change="onDateChange"
        />
      </FormItem>
    </Form>
    <div class="table-content">
      <Table height="450" border :columns="list.columns" :data="list.data" />
    </div>
    <div slot="footer">
      <Button @click="onCancel">取消</Button>
      <Button type="primary" @click="onSave">确定</Button>
    </div>
  </Modal>
</template>

<script>
export default {
  data () {
    const validateDate = (rule, value, callback) => {
      if (value[0] === '' || value[1] === '') {
        callback(new Error('生效时间不能为空'))
      } else {
        callback()
      }
    }
    return {
      show: false,
      id: '',
      form: {
        policyName: '',
        date: [],
        beginDate: '',
        endDate: ''
      },
      rules: {
        policyName: [{ required: true, message: '政策名称不能为空', trigger: 'blur' }],
        date: [{ validator: validateDate, trigger: 'blur' }]
      },
      storeTypeList: [],
      originalListData: [],
      list: {
        data: [],
        columns: [
          { title: '门店类型', key: 'storeTypeName', align: 'left' },
          {
            title: '升级后计算政策的门店类型', key: 'upgradeStoreTypeName', align: 'left',
            render: (h, params) => {
              return <div>
                <i-select label-in-value clearable value={params.row.upgradeStoreTypeId} transfer onOn-change={ (e) => { this.handleUpgradeStoreTypeName(e, params) } } >
                  { this.storeTypeList.map(item => {
                    return <i-option disabled={params.row.storeTypeName === item.label} value={item.value} key={item.value}>{item.label}</i-option>
                  })}
                </i-select>
              </div>
            }
          },
          {
            title: '升级门槛(%)', key: 'upgradeThreshold', align: 'left',
            render: (h, params) => {
              return h('InputNumber', {
                props: {
                  min: 0,
                  max: 999,
                  value: params.row.upgradeThreshold
                },
                on: {
                  'on-change': (e) => {
                    const newData = this.list.data[params.index]
                    newData.upgradeThreshold = e
                    this.$set(this.list.data, params.index, newData)
                  }
                }
              })
            }
          }
        ]
      }
    }
  },
  mounted () {
    this.getStoreTypeList()
  },
  methods: {
    open (item) {
      if (item) {
        this.id = item.id
        this.form.policyName = item.policyName
        this.form.date = [new Date(item.beginDate), new Date(item.endDate)]
        this.form.beginDate = item.beginDate
        this.form.endDate = item.endDate
        this.list.data = this.originalListData.map(data1 => {
          const newData = { ...data1 }
          item.policyItems.forEach(data2 => {
            if (data1.storeTypeId === data2.storeTypeId) {
              newData.upgradeStoreTypeName = data2.upgradeStoreTypeName
              newData.upgradeStoreTypeId = data2.upgradeStoreTypeId
              newData.upgradeThreshold = data2.upgradeThreshold
            }
          })
          return newData
        })
      } else {
        this.form = {
          policyName: '',
          date: [],
          beginDate: '',
          endDate: ''
        }
        this.list.data = this.originalListData.map(item => {
          return {
            storeTypeName: item.storeTypeName,
            storeTypeId: item.storeTypeId,
            upgradeStoreTypeName: '',
            upgradeStoreTypeId: '',
            upgradeThreshold: ''
          }
        })
      }
      this.show = true
    },
    getStoreTypeList () {
      this.$ajaxGet('/storeType/findAll').then(res => {
        this.storeTypeList = res.map(item => {
          return {
            value: item.id,
            label: item.name
          }
        })
        this.originalListData = res.map(item => {
          return {
            storeTypeName: item.name,
            storeTypeId: item.id,
            upgradeStoreTypeName: '',
            upgradeStoreTypeId: '',
            upgradeThreshold: ''
          }
        })
      })
    },
    onDateChange (e) {
      this.form.beginDate = e[0] && e[0] + ' 00:00:00'
      this.form.endDate = e[1] && e[1] + ' 23:59:59'
    },
    handleUpgradeStoreTypeName (e, params) {
      const newData = this.list.data[params.index]
      newData.upgradeStoreTypeName = e ? e.label : ''
      newData.upgradeStoreTypeId = e ? e.value : ''
      this.$set(this.list.data, params.index, newData)
    },
    onSave () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const params = {
            policyName: this.form.policyName,
            endDate: this.form.endDate,
            beginDate: this.form.beginDate,
            quarterRebatePolicyItems: this.list.data.filter(item => item.upgradeStoreTypeName && item.upgradeThreshold)
          }
          if (this.id) params.id = this.id
          if (params.quarterRebatePolicyItems.length === 0) {
            this.$Notice.error({
              title: '最少需有一个门店类型'
            })
            return
          }
          const url = this.id ? '/setting/quarter_rebate_policy/modify' : '/setting/quarter_rebate_policy/save'
          this.$jsonPost(url, params).then(res => {
            if (res) {
              this.$Notice.success({
                title: `${this.id ? '更新' : '新增'}成功`
              })
              this.show = false
              this.$emit('complete')
            }
          })
        }
      })
    },
    onCancel () {
      this.show = false
    }
  }
}
</script>

<style>

</style>
